/**
 * 
 */
package pt.mleiria.bit;

import static java.lang.Integer.toBinaryString;
import static java.lang.Long.toHexString;

import org.apache.log4j.Logger;

/**
 * @author NB13712
 *
 */
public class BytesConverter {
	private static final Logger LOG = Logger.getLogger(BytesConverter.class);
	/**
	 * 
	 * @param word
	 * @return
	 */
	public static String wordToBinary(final String word){
		final char[] wordChars = word.toCharArray();
		String result = "";
		for(int i = 0; i < wordChars.length; i++){
			result += toBinaryString(wordChars[i]) + " ";
		}
		return result;
	}
	/**
	 * 
	 * @param i
	 * @return
	 */
	public static String intToHexa(final int i){
		return Integer.toHexString(i);
	}
	/**
	 * 
	 * @param i
	 * @return
	 */
	public static String intToBinary(final int i){
		return toBinaryString(i);
	}
	/**
	 * 
	 * @param binary
	 * @return
	 */
	public static String binaryToString(final String binary){
		final int charCode = Integer.parseInt(binary, 2);
		final String str = new Character((char)charCode).toString();
		return str;
	}
	/**
	 * 
	 * @param word
	 * @return
	 */
	public static String wordToHexa(final String word){
		final char[] wordChars = word.toCharArray();
		String result = "";
		for(int i = 0; i < wordChars.length; i++){
			result += Integer.toHexString(wordChars[i]) + " ";
		}
		return result;
	}
	/**
	 * 
	 * @param l
	 * @return
	 */
	public static String longToHexa(final long l){
		return toHexString(l);
	}
	/**
	 * 
	 * @param hex
	 * @return
	 */
	public static String fromHexadecimalToBinary(final String hex) {
		int i = Long.valueOf(hex, 16).intValue();
		String by = Integer.toBinaryString(i);
		return by;
	}
	/**
	 * 
	 * @param hex
	 * @return
	 */
	public static String fromHexadecimalToBinary(final int hex) {
		String by = Integer.toBinaryString(hex);
		return by;
	}
	/**
	 * 
	 * @param hex
	 * @return
	 */
	public static int fromHexadecimalToInteger(final String hex) {
		int i = Integer.valueOf(hex, 16).intValue();
		return i;
	}
	/**
	 * 
	 * @param s
	 * @return
	 */
	public static byte[] hexStringToByteArray(String s) {
	    int len = s.length();
	    byte[] data = new byte[len / 2];
	    for (int i = 0; i < len; i += 2) {
	        data[i / 2] = (byte) ((Character.digit(s.charAt(i), 16) << 4)
	                             + Character.digit(s.charAt(i+1), 16));
	    }
	    return data;
	}

}
